package com.ruoyi.notify.service.impl;


import com.ruoyi.common.core.domain.NotifyLogVo;
import com.ruoyi.common.rabbitmq.constant.RabbitmqConstants;
import com.ruoyi.common.rabbitmq.domain.EmailFileTemplate;
import io.netty.channel.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

@Service
public class EmailFileServiceImpl {

    private static final String ALIDM_SMTP_HOST = "smtpdm.aliyun.com";
    private static final String ALIDM_SMTP_PORT = "80";

    @Value("${aliyun.mail.user}")
    private String MAIL_USER ;

    @Value("${aliyun.mail.password}")
    private  String MAIL_PASSWORD ;

    @Value("${aliyun.mail.path}")
    private  String PATH_HOME;

//    @Autowired
//    RemoteNotifyLogService remoteNotifyLogService;

    @RabbitListener(queues = {RabbitmqConstants.EMAIL_FILE_QUEUE})
    @RabbitHandler
    public  void emailFileSend(EmailFileTemplate emailFileTemplate, org.springframework.amqp.core.Message mqMessage, Channel channel) throws IOException {
       // channel.basicAck(mqMessage.getMessageProperties().getDeliveryTag(),true);
        String targetE = emailFileTemplate.getTargetEmails();
        StringBuilder tmp = new StringBuilder();
        if(targetE != null){
            String[] split = targetE.split(",");
            for(int i = 0;i<split.length;i++){
                if(split[i] != null && !split[i].equals("")){
                    tmp.append(split[i]);
                    if((split.length - 1) > i){
                        tmp.append(",");
                    }
                }
            }
            emailFileTemplate.setTargetEmails(tmp.toString());
        }


        Session mailSession = loadMailSession();
        String errorCode = null;
        try {
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址,比如xxx@xxx.com。和上面的mail.user保持一致。名称用户可以自定义填写。
            InternetAddress from = new InternetAddress(MAIL_USER, emailFileTemplate.getFromAlias());
            message.setFrom(from);


            // 设置收件人邮件地址，比如yyy@yyy.com
            String[] targetEmails = emailFileTemplate.getTargetEmails().split(",");
            InternetAddress[] adds = new InternetAddress[targetEmails.length];
            for(int i = 0;i < targetEmails.length; i++){
              //  adds[i] = new InternetAddress(targetEmails[i]);
                System.out.println(targetEmails[i]);
                adds[i] = new InternetAddress("284486912@qq.com");
            }

            message.setRecipients(Message.RecipientType.TO, adds);

            // 设置邮件标题
            message.setSubject(emailFileTemplate.getSubject());

            // 发送附件，总的邮件大小不超过15M，创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            messageBodyPart.setText(emailFileTemplate.getTextBody());

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            List<String> fileList = emailFileTemplate.getFileName();
            List<byte[]> contents = emailFileTemplate.getContents();
            for(int i = 0;i < fileList.size(); i++){
                MimeBodyPart mbpFile = new MimeBodyPart();
                String filePath = byte2File(fileList.get(i), contents.get(i));
                FileDataSource source = new FileDataSource(filePath);
                mbpFile.setDataHandler(new DataHandler(source));
                mbpFile.setFileName(MimeUtility.encodeText(fileList.get(i)));
                mbpFile.addHeader("Content-Transfer-Encoding", "base64");
                multipart.addBodyPart(mbpFile);
            }
            // 发送含有附件的完整消息
            message.setContent(multipart);
            // 发送附件代码，结束
            // 发送邮件
            Transport.send(message);
        }
        catch (MessagingException | UnsupportedEncodingException e) {
            if(e.getMessage().length() > 200){
                errorCode = e.getMessage().substring(0,199);
            }else{
                errorCode = e.getMessage();
            }

            // 在这里处理message内容， 格式是固定的
            System.out.println(errorCode);
        } finally {
            List<NotifyLogVo>  vos = new LinkedList<>();
            List<Long> notifyUserIds = emailFileTemplate.getNotifyUserId();
            List<String> notifyUserNames = emailFileTemplate.getNotifyUserName();
            for(int i = 0;i < notifyUserIds.size(); i++){
                NotifyLogVo vo = new NotifyLogVo();
                vo.setContent(emailFileTemplate.getTextBody());
                vo.setNotifyStatus(2);
                vo.setNotifyTime(System.currentTimeMillis());
                vo.setNotifyUserId(notifyUserIds.get(i));
                vo.setNotifyUserName(notifyUserNames.get(i));
                vo.setNotifyType(4);
                vo.setRemark(errorCode);
                String s = Long.toString(mqMessage.getMessageProperties().getDeliveryTag());
                System.out.println(s);
                vo.setMessageId(s);
                vos.add(vo);
            }

            try{
//                remoteNotifyLogService.addNotify(vos);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private String byte2File(String fileName,byte[] content){
        File dir = new File(PATH_HOME);
        if(!dir.exists()){
            dir.mkdir();
        }
        String path = PATH_HOME + fileName;
        FileOutputStream o = null;
        File f1= new File(path);
        try {
            o = new FileOutputStream(f1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            o.write(content);
            o.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                o.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }


    private Session loadMailSession() {
        try {
            // 配置发送邮件的环境属性
            final Properties props = new Properties();
            // 表示SMTP发送邮件，需要进行身份验证
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", ALIDM_SMTP_HOST);
            props.put("mail.smtp.port", ALIDM_SMTP_PORT);

            // 发件人的账号
            props.put("mail.user", MAIL_USER);
            // 访问SMTP服务时需要提供的密码
            props.put("mail.password", MAIL_PASSWORD);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            return Session.getInstance(props, authenticator);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("mail session is null");
        }
        return null;
    }

}
